﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MusicDownload
{
    public class MusicModel
    {
        [JsonProperty(PropertyName = "author")]
        public string Author { get; set; }

        [JsonProperty(PropertyName = "link")]
        public string Link { get; set; }

        [JsonProperty(PropertyName = "lrc")]
        public string Lrc { get; set; }

        [JsonProperty(PropertyName = "pic")]
        public string Pic { get; set; }

        [JsonProperty(PropertyName = "songid")]
        public long SongId { get; set; }

        [JsonProperty(PropertyName = "title")]
        public string Title { get; set; }

        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

        [JsonProperty(PropertyName = "url")]
        public string Url { get; set; }
    }

    public static class MusicSeacher
    {
        public static List<MusicModel> Search(string input)
        {
            var text = HttpPost("http://music.liuzhijin.cn/", $"input={HttpUtility.UrlEncode(input)}&filter=name&type=netease&page=1");
            //var text = HttpPost("http://music.liuzhijin.cn/", "input=%E7%87%83%E7%83%A7%E6%88%91%E7%9A%84%E5%8D%A1%E8%B7%AF%E9%87%8C&&filter=name&type=netease&page=1");
            if (string.IsNullOrEmpty(text))
                return null;

            var back_data = (JObject)JsonConvert.DeserializeObject(text);
            if (!string.IsNullOrEmpty((string)back_data["error"]))
                throw new Exception((string)back_data["error"]);

            if ((int)back_data["code"] != 200)
                throw new Exception($"出错了，错误编码为 {back_data["code"]}");

            return back_data["data"].ToObject<List<MusicModel>>();
        }

        private static string HttpPost(string url, string input)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                var data = Encoding.ASCII.GetBytes(input);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers["X-Requested-With"] = "XMLHttpRequest";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();

                return new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            }
            catch (Exception)
            {
                return string.Empty;
            }

        }
    }
}
